package tang.server;

import java.net.InetSocketAddress;
import java.util.concurrent.CountDownLatch;

/**
 * @author Tang
 * @classname ZKServerMain
 * @description [  ]
 * @date 2021/2/28 20:53
 */
public class ZKServerMain {

    private final String host = "127.0.0.1";
    private final Integer port = 9000;

    private NioServerCnxnFactory nioServerCnxnFactory;

    public static void main(String[] args) {
        ZKServerMain zkServerMain = new ZKServerMain();
        try {
            zkServerMain.initializeAndRun();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initializeAndRun() throws Exception {

        CountDownLatch countDownLatch = new CountDownLatch(1);

        ZkServer zkServer = new ZkServer();
        zkServer.registerZkServerShutdownHandler(new ZkServerShutdownHandler(countDownLatch));

        this.nioServerCnxnFactory = createFactory();
        assert this.nioServerCnxnFactory != null;
        this.nioServerCnxnFactory.configure(new InetSocketAddress(host, port));

        this.nioServerCnxnFactory.startUp(zkServer);

        countDownLatch.await();
        shutdown();

        this.nioServerCnxnFactory.join();
    }

    private void shutdown() {
        if (this.nioServerCnxnFactory != null) {
            this.nioServerCnxnFactory.shutdown();
        }
    }

    private NioServerCnxnFactory createFactory() {
        try {
            Class<?> aClass = Class.forName("tang.server.NioServerCnxnFactory");
            return (NioServerCnxnFactory) aClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}